﻿using System;
using System.Collections.Generic;
using IBNet.UtilsDataStructuresAndExtensions;

namespace IBNet.DayTrade.Indicators
{
   public class LowestLow : Indicator
   {
      private readonly int startIndex;
      private readonly int forLoopEndIndex;
      private readonly int numberOfBarsNeeded;

      public LowestLow(int startIndex, int endIndex, string name)
         : base(name)
      {
         if (startIndex >= endIndex)
            throw new ArgumentException("startIndex must be less than endIndex");
         if (startIndex < 0 || endIndex < 0)
            throw new ArgumentException("startIndex and endIndex must be greater than or equal to 0.");
         if (String.IsNullOrEmpty(name))
            throw new ArgumentNullException("name");

         this.startIndex = startIndex;
         this.forLoopEndIndex = endIndex + 1;
         this.numberOfBarsNeeded = forLoopEndIndex - startIndex;
      }

      public LowestLow(int startIndex, int endIndex) :
         this(startIndex, endIndex, "LowestLow")
      {
      }

      public override decimal? CalculateIndicator(FixedLengthCollection<PriceBar> priceBars)
      {
         if (priceBars.Count < numberOfBarsNeeded)
            return null;

         decimal lowestLow = priceBars[startIndex].Low;

         for (int i = startIndex + 1; i != forLoopEndIndex; ++i)
         {
            if (priceBars[i].Low < lowestLow)
            {
               lowestLow = priceBars[i].Low;
            }
         }
         return lowestLow;
      }
   }
}
